package com.miaosha.ms_05.controller;

import com.miaosha.ms_05.domain.OrderInfo;
import com.miaosha.ms_05.domain.User;
import com.miaosha.ms_05.exception.GlobalException;
import com.miaosha.ms_05.result.CodeMsg;
import com.miaosha.ms_05.result.Result;
import com.miaosha.ms_05.service.GoodsService;
import com.miaosha.ms_05.service.MiaoshaService;
import com.miaosha.ms_05.vo.GoodsVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * @Description //TODO
 * @Author Administrator
 * @DATE 2020/9/19 16:09
 **/
@Controller
@RequestMapping("/miaosha")
public class MiaoshaController {

    @Autowired
    private MiaoshaService miaoshaService;

    @RequestMapping("/do_miaosha")
    @ResponseBody
    public Result<String> buy(User user, @RequestParam("goodsId") Long goodsId) {
        try {
            GoodsVo goods = miaoshaService.getGoodsVoByIdFromRedis(goodsId);
            if (goods == null) {
                return Result.error(CodeMsg.GOOD_NOT_EXIST);
            }
            //库存校验
            Integer stockCount = goods.getStockCount();
            if (stockCount <= 0) {
                return Result.error(CodeMsg.STOCK_NOT_ENOUGH);
            }
            miaoshaService.buyGoods(goods, user);
        } catch (GlobalException e) {
            return Result.error(e.getCodeMsg());
        } catch (Exception e) {
            return Result.error(CodeMsg.SERVER_ERR);
        }
        return Result.success(CodeMsg.SUCCESS.getMsg());
    }

    @RequestMapping("/reset")
    @ResponseBody
    public Result<String> reset() {
        miaoshaService.rest();
        return Result.success("OK");
    }
}
